<?php
// 数据库连接信息
include '../dbconnect.php';

// 获取表单数据
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$service = $_POST['service'];
$message = $_POST['message'];
$date = $_POST['date'];

// 生成唯一的 APPOINTMENT_ID
function generateAppointmentId($conn) {
	// 获取当前所有的 APPOINTMENT_ID 并排序
	$sql = "SELECT APPOINTMENT_ID FROM appointment ORDER BY APPOINTMENT_ID DESC LIMIT 1";
	$result = $conn->query($sql);
	$row = $result->fetch_assoc();
	$max_id = $row['APPOINTMENT_ID'];

	if ($max_id === null) {
		$next_id = 1;
	} else {
		$last_number = intval(substr($max_id, 13)); // 假设前缀是 "appointmentId__"
		print_r($last_number);
		$next_id = $last_number + 1;
	}

	return "Appointment_" . str_pad($next_id, 3, '0', STR_PAD_LEFT);
}
$appointment_id = generateAppointmentId($conn);

// 插入数据到数据库
$sql = "INSERT INTO appointment (APPOINTMENT_ID, APPOINTMENT_USER_NAME, APPOINTMENT_USER_EMAIL, APPOINTMENT_USER_PHONE, APPOINTMENT_SERVICE_TYPE, APPOINTMENT_SERVICE_DESC, APPOINTMENT_SERVICE_TIME) VALUES (?, ?, ?, ?, ?, ?, ?)";

$stmt = $conn->prepare($sql);
$stmt->bind_param("sssssss", $appointment_id, $name, $email, $phone, $service, $message, $date);

if ($stmt->execute()) {
    echo "Appointment submitted successfully!";
	 // 提交成功，显示提示信息并重定向
	echo '<script type="text/javascript">';
	echo 'alert("Appointment submitted successfully!");';
	echo 'window.location.href = "6_appointment.php";';
	echo '</script>';
} else {
    echo "Error: " . $stmt->error;
}

$stmt->close();
$conn->close();
?>